package com.googlecode.jwsm.security.caching;

import java.io.Serializable;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.jwsm.security.SecurityFactory;
import com.googlecode.jwsm.security.User;

public class CachingSecurityFactory implements SecurityFactory {
	private SecurityFactory factory;
	private HashMap cache;
	private long timeout;

	public CachingSecurityFactory(SecurityFactory factory, long timeout) {
		this.factory = factory;
		cache = new HashMap();
		this.timeout = timeout;
	}

	public Object getApplicationProperty(String name) {
		String key = "appProperty:" + name;
		CachedObject cached = (CachedObject) cache.get(key);
		if (cached == null) {
			cached = new CachedObject(factory.getApplicationProperty(name),
					timeout);
			cache.put(key, cached);
		} else if (cached.isExpired())
			cached.set(factory.getApplicationProperty(name));
		return cached;
	}

	public User login(String username, String password) {
		User user = factory.login(username, password);
		if (user == null)
			return null;
		else
			return new CachedUser(user, timeout);
	}

	public User login(HttpServletRequest request, HttpServletResponse response,
			String formURL) {
		User user = factory.login(request, response, formURL);
		if (user == null)
			return null;
		else
			return new CachedUser(user, timeout);
	}

	public User login(HttpServletRequest request, HttpServletResponse response) {
		User user = factory.login(request, response);
		if (user == null)
			return null;
		else
			return new CachedUser(user, timeout);
	}

	public void logout(HttpServletRequest request,
			HttpServletResponse response, String formURL) {
		factory.logout(request, response, formURL);
	}

	public void setApplicationProperty(String name, Serializable object) {
		factory.setApplicationProperty(name, object);
		String key = "appProperty:" + name;
		CachedObject cached = new CachedObject(object, timeout);
		cache.put(key, cached);
	}
}
